<template>
  <div class="music-page">
    <!-- 上半部分 -->
    <div class="top-half">
      <!-- 左侧：图片和歌曲信息 -->
      <div class="left-part">
        <img :src="'http://localhost:8080/images/upload/' + music.cover_image" alt="Album Cover" class="album-image" />
          <div class="song-info">
            <h2 class="song-title">{{ music.music_name }}</h2>
            <p>歌手：{{ music.artist }}</p>
            <p>类型：{{ music.type }}</p>
          </div>
        <!-- 歌词区域 -->
        <div class="lyrics-box" ref="lyricsBox" @mousemove="handleMouseMove" @mouseleave="scrollToCurrentLyric">
          <div v-for="(line, index) in lyrics" :key="index" :class="{ 'highlight': index === currentLineIndex }">
              {{ line.text }}
          </div>
        </div>

      </div>

      <!-- 右侧：按钮和表格 -->
      <div class="right-part">
        <div class="function-buttons">
          <audio ref="audioPlayer" controls class="audio-player">  
            <source :src="'http://localhost:8080/images/upload/' + currentAudio" type="audio/mpeg" muted playsinline />  
            您的浏览器不支持音频播放。  
          </audio>
          <div class="current-lyric">{{ currentLyricText }}

          </div>
            <el-button type="primary" round @click="handlelike">{{ isCollected ? "已收藏" : "收藏" }}</el-button>

            <!-- <el-button type="primary" round @click="playMusic(music.audio,music.music_id)">播放</el-button>   -->
            <el-button type="primary" round @click=" goToComment(music)">评论</el-button>
      
        </div>
        <!-- 表格区域 -->
        <div class="table-box">
           <!-- 表格区域 -->
              <el-table
                :data="musics"
                style="width: 150%"
                @selection-change="handleSelectionChange"
                ref="multipleTable"
          
              >
            
                <!-- <el-table-column prop="music_id" label="序号" width="100" /> -->
                <el-table-column label="相似歌曲" type="index" width="100" align="center"></el-table-column>

                <el-table-column prop="cover_image" label="歌曲封面" width="150" >      
                  <template #default="scope">
                    <el-image
                      style="width: 100px; height: 100px"
                    :src="'http://localhost:8080/images/upload/' + scope.row.cover_image"/>
                    </template>
                </el-table-column>

          
                <el-table-column prop="music_name" label="乐曲名" width="150" />
                <el-table-column prop="artist" label="音乐人" width="150" />
                <el-table-column prop="duration" label="歌曲播放量" width="100" />
                
                <el-table-column prop="type" label="歌曲类型" width="100" />
                <!-- 操作列 -->
                <el-table-column fixed="right" label=" " min-width="100">
                  <template v-slot="scope">
           
                    
                    <el-button type="info" @click="openDetailDialog(scope.row.music_id)">详情</el-button>
                    <el-button type="primary" @click="goBackAndRefresh(scope.row.music_id, scope.row.type)">播放</el-button>
                  
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页显示 -->
              <el-pagination
                    :current-page.sync="currentPage"
                    :page-size="pageSize"
                    :total="totalItems"
                    layout="prev, pager, next"
                    @current-change="handlePageChange"
                  />
        </div>
        
      </div>
    </div>
    <!-- 下半部分 -->
    <div class="bottom-half">
      <!-- 这里可以放置其他内容 -->
    </div>
  </div>

  <el-dialog
  title="歌曲详情"
  v-model="dialogDetailVisible"
  width="1000"
  @close="resetForm">
  
  <el-form :model="form">
    <el-row>
      <el-col :span="12">
        <el-form-item label="歌曲名称" :label-width="formLabelWidth">
          <el-form-item :label="form.music_name" >
          </el-form-item>
        </el-form-item>
        <br>
        <el-form-item label="歌曲作者" :label-width="formLabelWidth">
          <el-form-item :label="form.artist" >
          </el-form-item>
        </el-form-item>
        <br>
        <el-form-item label="歌曲类型" :label-width="formLabelWidth">
          <el-form-item :label="form.type" >
          </el-form-item>
        </el-form-item>
        <br>
        <el-form-item label="歌曲播放量" :label-width="formLabelWidth">
          <el-form-item :label="form.duration" >
          </el-form-item>
        </el-form-item> 
        <br>
        <el-form-item label="歌曲时长" :label-width="formLabelWidth">
          <el-form-item :label="form.popularity" >
          </el-form-item>
        </el-form-item> 
      

    
      </el-col>
      <el-col :span="12">
        <!-- 歌词 -->
        <el-form-item label="歌词" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            v-model="form.lyrics"
            readonly
            class="text-area-scrollable"
            :rows="8"> <!-- 设置行数为5，根据需要调整 -->
          </el-input>
        </el-form-item>
        <br>
        <el-form-item label="歌曲简介" :label-width="formLabelWidth">
          <el-input
          type="textarea"
          v-model="form.description"
          readonly
          class="text-area-scrollable"
          :rows="8"> <!-- 设置行数为5，根据需要调整 -->
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 根据需要添加更多的表单项 -->
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogDetailVisible = false">取消</el-button>
    </div>
  </template>
</el-dialog>
</template>

<script>  

import { ElMessage, ElMessageBox } from 'element-plus';  
import axios from 'axios'; 
export default {  
  data() {  
    return {  
      // 歌曲数据对象  
      music: {  
        cover_image: '',  
        music_name: '',  
        artist: '',  
        type: '',  
        play_count: 0,  
        description: ''  
      },  
      dialogDetailVisible:false, // 详细对话框
      currentPage: 1, // 当前页码
      pageSize:  5,// 每页显示的条目数
      totalItems: 0, // 总条目数
      musics:[],
      form:[],
      // 当前显示的内容  
      currentContent: '',  
      // 是否显示名人点评  
      isReview: true,  
      isCollected:false,   //初始化为"收藏歌曲"
      // 是否显示歌词  
      isLyrics: false,  


      lyrics: [],
      currentLineIndex: 0,


      autoScrollEnabled: true, // 控制自动滚动

      mouseIsMoving: false, // 标记鼠标是否正在移动
      scrollTimeout: null, // 用于存储定时器
    };  
  },  

  methods: {  
    watch: {
    '$route.query': {
      handler(newValue) {
        // 当查询参数变化时重新加载数据
        this.music_id = newValue.music_id;
        this.searchtype = newValue.type;

        // 调用数据加载方法
        this.fetchSongs().then(() => {
          // 成功后处理逻辑
        }).catch(error => {
          console.error('Error fetching songs:', error);
        });
      },
      immediate: true // 立即执行一次
    }
  },


    //回调当前页面
    goBackAndRefresh(musicId, type) {
  console.log("准备跳转到当前页面，传递参数：", musicId, type); // 调试信息

  this.music_id = musicId; // 先更新数据
  this.searchtype = type; // 更新类型

  this.$router.push({ 
    path: this.$route.path, // 保持在当前路径
    query: { 
      music_id: this.music_id,  // 传递 music_id
      type: this.searchtype      // 传递 type
    } 
  }).then(() => {
    // 直接重新加载当前页面
    this.$router.go(0); // 强制重新加载当前页面
  }).catch(error => {
    console.error("跳转失败:", error); // 捕获并输出跳转错误
  });
},


    playMusic(audio, music_id) {
      this.currentAudio = audio; 
      console.log("当前音频源:", this.currentAudio);
      this.$nextTick(() => {
        const audioPlayer = this.$refs.audioPlayer;
        if (audioPlayer) {
          audioPlayer.src = `http://localhost:8080/images/upload/${this.currentAudio}`; 
          audioPlayer.load(); 
          
          audioPlayer.play().then(() => {
            console.log("播放成功");
            this.incrementPlayCount(music_id);
            audioPlayer.addEventListener('timeupdate', () => {
              this.updateLyrics(audioPlayer.currentTime);
            });
          }).catch(error => {
            console.error('播放失败:', error);
          });
        } else {
          console.error("音频播放器引用未定义。");
        }
      });
    },
    handleMouseMove() {
    this.mouseIsMoving = true; // 用户正在滑动鼠标，允许自动滚动
    this.autoScrollEnabled = false; // 停止自动滚动
    clearTimeout(this.scrollTimeout); // 清除之前的定时器

    // 设置一个定时器，在 3 秒后恢复自动滚动
    this.scrollTimeout = setTimeout(() => {
      this.mouseIsMoving = false; // 标记鼠标不再移动
      this.autoScrollEnabled = true; // 恢复自动滚动
      this.scrollToCurrentLyric(); // 滚动到当前播放的歌词
    }, 2000); // 3 秒的延迟
  },
  scrollToCurrentLyric() {
    // 鼠标离开时滚动到当前歌词
    const lyricsBox = this.$refs.lyricsBox;
    const lineHeight = 24; // 假设每行歌词的高度
    const halfBoxHeight = 150; // 歌词框一半的高度
    const scrollTo = (this.currentLineIndex * lineHeight) - halfBoxHeight + (lineHeight / 2);
    lyricsBox.scrollTop = scrollTo; // 滚动到中间
  },
  updateLyrics(time) {
    console.log(`Timeupdate event triggered at ${time} seconds`);
    let currentIndex = -1; 
    for (let i = 0; i < this.lyrics.length; i++) {
      if (this.lyrics[i].time > time) {
        currentIndex = i - 1;
        break;
      }
      currentIndex = i;
    }
    if (currentIndex !== -1) {
      this.currentLineIndex = currentIndex; 
      this.currentLyricText = this.lyrics[currentIndex].text; 
      // 在更新歌词时调用滚动，只有当鼠标不移动时调用
      if (!this.mouseIsMoving) {
        this.scrollToCurrentLyric();
      }
    }
  },


loadLyrics(lyricsText) {          //解析歌词方法
  console.log("Loading lyrics..."); // 调试信息：开始加载歌词
  this.lyrics = this.$parseLyrics(lyricsText); // 使用全局的 parseLyrics 函数
  console.log("Lyrics loaded:", this.lyrics); // 调试信息：加载的歌词数据
  if (this.lyrics.length === 0) {
    console.error("No lyrics were parsed, check the lyrics text format."); // 调试信息：没有解析到歌词
  }
},


    beforeDestroy() {       //监听歌词播放事件
  const audioPlayer = this.$refs.audioPlayer;
  if (audioPlayer) {
    audioPlayer.removeEventListener('timeupdate', this.updateLyrics);
  }
},

 

       //检查是否已经收藏
   checkIfCollectedMusic() {
    axios
      .get(`/mc/MusicCollectioncheck`, {
        params: { user_id:this.userId, music_id: this.music_id},
      })
      .then((response) => {
        this.isCollected = response.data.collected; // 设置每条的收藏状态
      })
      .catch((error) => {
        console.error("检查收藏状态失败：", error);
      });
},
  
    //收藏
    handlelike() {  
    const url = this.isCollected ? `/mc/MusicCollectiondelete` : `/mc/MusicCollectionadd`;
    const data = { user_id:this.userId, music_id: this.music_id };
    axios({
    method: this.isCollected ? "delete" : "post", 
    url,
    data,
  })
  .then((response) => {
    if (response.data.success) {
      this.isCollected = !this.isCollected; // 切换收藏状态

      const message = this.isCollected ? "收藏成功" : "取消收藏成功";
      ElMessage.success(message);
    } else {
      ElMessage.error("操作失败，请稍后再试！");
    }
  })
  .catch((error) => {
    console.error("收藏操作失败：", error);
    ElMessage.error("网络错误，请稍后重试！");
  });
    },  
    


        openDetailDialog(music_id){     //打开详情对话框
                var _this=this
                this.$http.get("music/g1/"+music_id).then(function(response){
                console.log(response.data);
                _this.form=response.data
              })

                this.dialogDetailVisible=true
                

        },



        handlePageChange(page) {      //分页回调
      console.log("Changing page to:", page); // 调试输出
      this.currentPage = page;

        this.fetchMusics();

    },
    goToComment(music){
    
      console.log(music.music_id)
      sessionStorage.setItem('music_id', music.music_id);
      this.$router.push({name:'Comment'},music)

    },

    // 获取歌曲数据的方法  

    fetchSongs() {
  return fetch(`http://localhost:8080/music/g1/${this.music_id}`)
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => {
      this.music = data;
      console.log(this.music);
      this.lyricsText = this.music.lyrics;
      this.loadLyrics(this.lyricsText);
      console.log(this.lyricsText);
    })
    .catch(error => {
      console.error('Error fetching songs:', error);
    });
}, 

    fetchMusics() {        //获取同类型歌曲
  let params = `page=${this.currentPage}&size=${this.pageSize}`;
  if (this.searchname) {
    params += `&music_name=${encodeURIComponent(this.searchname)}`;
  }
  if (this.searchmanname) {
    params += `&artist=${encodeURIComponent(this.searchmanname)}`;
  }
  if (this.searchtype && this.searchtype !== "所有歌曲类型") {
    params += `&type=${encodeURIComponent(this.searchtype)}`;
  }
  console.log(`Request URL: http://localhost:8080/music/search?${params}`);

  fetch(`http://localhost:8080/music/search?${params}`)
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => {
      console.log("Fetched data:", data);
      this.musics = data.list;
      this.totalItems = data.total;
      this.currentPage = data.pageNum; // 确保这里更新 currentPage
    })
    .catch(error => console.error('Error fetching songs:', error));
},
    




    incrementPlayCount(music_id) {
      // 发送请求到后端，更新播放次数
      this.$http.post('/music/incrementPlayCount', { music_id }).then(response => {
        // 处理响应
        // this.fetchSongs(music_id); // 重新获取页面数据以更新播放次数
        this.fetchMusics(music_id); // 重新获取页面数据以更新播放次数
      }).catch(error => {
        console.error('更新播放次数失败', error);
      });
    },
    
   
 
  }, 
  mounted() {
  // 从查询参数中获取 music_id 和 type
  const { music_id, type } = this.$route.query;

  // 设置当前的 music_id 和 type
  this.music_id = music_id || sessionStorage.getItem('music_id');
  this.userId = localStorage.getItem('user_id');
  this.searchtype = type || sessionStorage.getItem('type');

  this.checkIfCollectedMusic(); // 检查笔记收藏状态
  this.fetchMusics(); // 获取同类型歌曲

  // 根据新的 music_id 获取歌曲数据
  if (this.music_id) {
    this.fetchSongs().then(() => {
      // 确保音乐数据已加载
      if (this.music && this.music.audio) {
        this.playMusic(this.music.audio, this.music.music_id);
      }
    }).catch(error => {
      console.error('Error fetching songs:', error);
    });
  }
},

};  
</script>  
<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;700&display=swap'); 

/* 歌词样式 */


.lyrics-box {
  height: 400px; /* 设置一个固定的高度 */
  overflow-y: auto; /* 当内容超出高度时，启用垂直滚动 */
  font-size: 16px;
  line-height: 24px;
  position: relative; /* 确保可以使用绝对定位 */
}



.lyrics-box::-webkit-scrollbar {
  width: 0; /* 隐藏垂直滚动条 */
  background: transparent; /* 背景透明 */
}

.highlight {
  color: red;
  font-weight: bold;
}

body {
  font-family: 'Noto Sans SC', sans-serif;
  background-color: #f4f4f9; 
  color: #333; /* 默认文本颜色 */
}

.music-page {
  background-color: #ffffff; /* 容器背景色 */
  box-shadow: 0 2px 4px rgba(0,0,0,0.1); /* 添加阴影，增加层次感 */
}

.el-button {  
  width: 80px;  
  background-color: #f9f4e8;
  color: #4b3f33;
} 

.music-page {
  display: flex;
  flex-direction: column;
}

.top-half {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.left-part {
  flex: 3;
  padding: 20px;
  display: flex; /* 使用 Flexbox 布局 */
  flex-direction: column; /* 垂直排列子元素 */
  justify-content: center; /* 垂直居中 */
  align-items: center; /* 水平居中 */
  text-align: center; /* 使文本居中 */
}

.right-part {
  flex: 7;
  padding: 20px;
}

.album-image {
  width: 40%;
  height: auto;
  margin-bottom: 20px;
}

.song-info {
  margin-bottom: 20px;
}

.lyrics-text {
  width: 100%;
  height: 600px;
  resize: none;
  border: none; /* 去掉边框 */
  background-color: #ffffff; /* 设置背景颜色为白色 */
  padding: 20px; /* 增加内边距，数值可以根据需要调整 */
  font-family: 'KaiTi', serif; /* 设置字体为楷体，使用通用的serif作为后备字体 */
  font-size: 1em; /* 设置字体大小为当前字体大小的两倍，或者使用像素值如24px */
  outline: none; /* 当文本框获得焦点时，不显示轮廓 */
  box-shadow: none; /* 去掉文本框的阴影效果 */
  
}

/* 添加一个伪类选择器，当文本框获得焦点时应用 */
.lyrics-text:focus {
  border: none; /* 确保在获得焦点时也不显示边框 */
  outline: none; /* 确保在获得焦点时不显示轮廓 */
  box-shadow: none; /* 确保在获得焦点时不显示阴影 */
}

.function-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

audio {
  margin-right: auto; /* 将音频播放器推到容器的最左端 */
}

.table-box {
  height: 700px;
  overflow: auto;
}

.bottom-half {
  flex: 1;
}

/* 去除表格边框线 */
.el-table {
  border: none;
}

.el-table__body-wrapper::after, .el-table__header-wrapper::after {
  content: none;
}

.el-table .el-table__body, .el-table .el-table__header {
  th, td {
    border: none;
  }
}
.current-lyric {  
            padding: 10px 40px 20px 25px; /* 上、右、下、左的内边距 */  
            color: red;                   /* 字体颜色为红色 */  
            font-family: 'Dancing Script', cursive, sans-serif; /* 使用 Dancing Script 字体 */  
            font-size: 20px;             /* 设置字体大小为 24 像素 */  
        }  

</style>

<!-- 播放器样式 -->
<style>

.audio-player {
  width: 60%; /* 设置音频播放器宽度 */
  background-color: #eee5e5f7; /* 背景颜色 */
  border-radius: 50px; /* 圆角 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}

</style>